package edu.whut.mall.user.config;


import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.RequestHandler;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

/**
 * @program: d9lab-mall
 * @description: 文档接口配置类
 * @author: Wayne
 * @create: 2020-04-11 11:31
 **/
@Configuration
@EnableSwagger2
public class Swagger2Config {

    //配置swagger2核心配置 docket
    @Bean
    public Docket createRestApi(){
        return new Docket(DocumentationType.SWAGGER_2)  //指定api文档为swagger2类型
                       .apiInfo(apiInfo())              //文档的汇总信息
                       .select()
                       .apis(basePackage("edu.whut.mall.user.controller" + splitor + "edu.whut.mall.common.controller"))
                       .paths(PathSelectors.any())
                       .build();
    }

    private ApiInfo apiInfo(){
        return new ApiInfoBuilder()
                .title("d9lab电商重构")
                .contact(new Contact("d9lab","鉴主1805","728528220@qq.com"))
                .description("d9lab商城")
                .version("1.0.0")
                .termsOfServiceUrl("www.鉴主1805.com").build();
    }

    // 定义分隔符,配置Swagger多包
    private static final String splitor = ";";

    public static Predicate<RequestHandler> basePackage(final String basePackage) {
        return input -> declaringClass(input).transform(handlerPackage(basePackage)).or(true);
    }

    private static Function<Class<?>, Boolean> handlerPackage(final String basePackage)     {
        return input -> {
            // 循环判断匹配
            for (String strPackage : basePackage.split(splitor)) {
                boolean isMatch = input.getPackage().getName().startsWith(strPackage);
                if (isMatch) {
                    return true;
                }
            }
            return false;
        };
    }

    private static Optional<? extends Class<?>> declaringClass(RequestHandler input) {
        return Optional.fromNullable(input.declaringClass());
    }

}
